/**
 * @file lv_demo_music_lyric.c
 * 歌词显示页面组件
 */

/*********************
 *      INCLUDE
 *********************/
//导入库

//导入自定义头文件
#include "lv_demo_music.h"
#include "lv_demo_music_lyric.h"
#include "lv_demo_music_main.h"
#include "lv_demo_music_font.h"
#include "lrc_parser.h"
#include "utf-8_to_gbk.h"

/*********************
 *      DEFINE
 *********************/
#define LYRIC_LINE_HEIGHT      50    // 每行歌词高度
#define LYRIC_VISIBLE_LINES    5     // 可见歌词行数
#define LYRIC_FOCUS_OPA        LV_OPA_COVER  // 焦点行不透明度
#define LYRIC_NORMAL_OPA       LV_OPA_70     // 普通行不透明度
#define LYRIC_FADE_OPA         LV_OPA_50     // 淡化行不透明度

/**********************
 *      TYPEDEF
 **********************/
typedef struct {
    lv_obj_t *cont;              // 歌词容器
    lv_obj_t *lines[LYRIC_VISIBLE_LINES];  // 歌词行标签数组
    lv_style_t style_focus;      // 焦点行样式
    lv_style_t style_normal;     // 普通行样式
    lv_style_t style_fade;       // 淡化行样式
    LrcFile *current_lrc;        // 当前歌词文件
    uint32_t current_track_id;   // 当前歌曲ID
    uint32_t focus_index;        // 焦点行索引
    bool has_lyric;              // 是否有歌词数据
} lyric_controller_t;

/**********************
 *  STATIC VARIABLES
 **********************/
static lyric_controller_t lyric_ctrl;
static const lv_font_t *lyric_font_small;
static const lv_font_t *lyric_font_large;

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void lyric_create_styles(void);
static void lyric_create_ui(lv_obj_t *parent);
static void lyric_load_for_track(uint32_t track_id);
static void lyric_clear_display(void);
static void lyric_update_display(void);
static void lyric_scroll_to_focus(void);
static int32_t lyric_find_current_index(long current_time);

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

/**
 * @brief 创建歌词显示界面
 * @param parent 父对象
 * @return 创建的歌词容器对象
 */
lv_obj_t * lv_demo_music_lyric_create(lv_obj_t *parent)
{
    // 初始化字体
    lyric_font_small = &ShiYuan_black_Normal_16;
    lyric_font_large = &ShiYuan_black_Normal_22;

    // 初始化控制器
    memset(&lyric_ctrl, 0, sizeof(lyric_controller_t));
    lyric_ctrl.current_track_id = 0xFFFFFFFF; // 初始化为无效ID
    lyric_ctrl.focus_index = 0;
    lyric_ctrl.has_lyric = false;

    // 创建样式
    lyric_create_styles();

    // 创建UI
    lyric_create_ui(parent);

    return lyric_ctrl.cont;
}

/**
 * @brief 设置当前播放的歌曲
 * @param track_id 歌曲ID
 */
void lv_demo_music_lyric_set_track(uint32_t track_id)
{
    if (track_id == lyric_ctrl.current_track_id) {
        return; // 已经是当前歌曲
    }

    lyric_ctrl.current_track_id = track_id;
    lyric_load_for_track(track_id);
}

/**
 * @brief 更新歌词显示根据当前播放时间
 * @param current_time 当前播放时间（毫秒）
 */
void lv_demo_music_lyric_update_time(long current_time)
{
    if (!lyric_ctrl.has_lyric || !lyric_ctrl.current_lrc) {
        return;
    }

    int32_t new_index = lyric_find_current_index(current_time);

    // 只有当索引确实改变时才更新显示
    if (new_index != lyric_ctrl.focus_index) {
        lyric_ctrl.focus_index = new_index;
        lyric_update_display();

        // 只有当索引有效时才滚动
        if (new_index >= 0) {
            lyric_scroll_to_focus();
        }
    }
}

/**
 * @brief 获取歌词容器高度
 * @return 容器高度
 */
lv_coord_t lv_demo_music_lyric_get_height(void)
{
    return LYRIC_LINE_HEIGHT * LYRIC_VISIBLE_LINES;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/

/**
 * @brief 创建歌词显示样式
 */
static void lyric_create_styles(void)
{
    // 焦点行样式（当前播放的歌词行）
    lv_style_init(&lyric_ctrl.style_focus);
    lv_style_set_text_font(&lyric_ctrl.style_focus, lyric_font_large);
    lv_style_set_text_color(&lyric_ctrl.style_focus, lv_color_black());
    lv_style_set_text_opa(&lyric_ctrl.style_focus, LYRIC_FOCUS_OPA);
    lv_style_set_text_align(&lyric_ctrl.style_focus, LV_TEXT_ALIGN_CENTER);

    // 普通行样式（即将播放的歌词行）
    lv_style_init(&lyric_ctrl.style_normal);
    lv_style_set_text_font(&lyric_ctrl.style_normal, lyric_font_small);
    lv_style_set_text_color(&lyric_ctrl.style_normal, lv_color_black());
    lv_style_set_text_opa(&lyric_ctrl.style_normal, LYRIC_NORMAL_OPA);
    lv_style_set_text_align(&lyric_ctrl.style_normal, LV_TEXT_ALIGN_CENTER);

    // 淡化行样式（已播放的歌词行）
    lv_style_init(&lyric_ctrl.style_fade);
    lv_style_set_text_font(&lyric_ctrl.style_fade, lyric_font_small);
    lv_style_set_text_color(&lyric_ctrl.style_fade, lv_color_hex(0x8a86b8));
    lv_style_set_text_opa(&lyric_ctrl.style_fade, LYRIC_FADE_OPA);
    lv_style_set_text_align(&lyric_ctrl.style_fade, LV_TEXT_ALIGN_CENTER);
}

/**
 * @brief 创建歌词显示UI
 * @param parent 父对象
 */
static void lyric_create_ui(lv_obj_t *parent)
{
    // 创建歌词容器
    lyric_ctrl.cont = lv_obj_create(parent);
    lv_obj_remove_style_all(lyric_ctrl.cont);
    lv_obj_set_size(lyric_ctrl.cont, LV_HOR_RES, LYRIC_LINE_HEIGHT * LYRIC_VISIBLE_LINES);
    lv_obj_set_flex_flow(lyric_ctrl.cont, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(lyric_ctrl.cont, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_bg_opa(lyric_ctrl.cont, LV_OPA_TRANSP, 0);
    lv_obj_set_style_pad_all(lyric_ctrl.cont, 0, 0);
    lv_obj_set_style_border_width(lyric_ctrl.cont, 0, 0);

    // 创建歌词行标签
    for (int i = 0; i < LYRIC_VISIBLE_LINES; i++) {
        lyric_ctrl.lines[i] = lv_label_create(lyric_ctrl.cont);
        lv_obj_set_size(lyric_ctrl.lines[i], LV_HOR_RES - 40, LYRIC_LINE_HEIGHT);
        lv_label_set_text(lyric_ctrl.lines[i], "");
        lv_obj_set_style_text_align(lyric_ctrl.lines[i], LV_TEXT_ALIGN_CENTER, 0);
        lv_label_set_long_mode(lyric_ctrl.lines[i], LV_LABEL_LONG_SCROLL_CIRCULAR);
    }

    // 初始显示无歌词提示
    lv_label_set_text(lyric_ctrl.lines[LYRIC_VISIBLE_LINES / 2], "暂无歌词");
    lv_obj_add_style(lyric_ctrl.lines[LYRIC_VISIBLE_LINES / 2], &lyric_ctrl.style_normal, 0);
}

/**
 * @brief 加载指定歌曲的歌词
 * @param track_id 歌曲ID
 */
static void lyric_load_for_track(uint32_t track_id)
{
    // 释放之前的歌词文件
    if (lyric_ctrl.current_lrc) {
        lrc_free(lyric_ctrl.current_lrc);
        lyric_ctrl.current_lrc = NULL;
    }

    lyric_ctrl.has_lyric = false;
    lyric_ctrl.focus_index = 0;  // 重置为0，而不是-1

    // 构建歌词文件路径
    const char *filename = _lv_demo_music_get_filename(track_id);
    if (!filename || strcmp(filename, "null") == 0) {
        lyric_clear_display();
        return;
    }

    char lrc_path[256];
    snprintf(lrc_path, sizeof(lrc_path), "%s\\%s.lrc", soft_base_path_resource_lrc, filename);

    // 解析歌词文件
    lyric_ctrl.current_lrc = lrc_parse_file(utf8_to_gbk(lrc_path));
    if (!lyric_ctrl.current_lrc || lyric_ctrl.current_lrc->line_count == 0) {
        lyric_clear_display();
        return;
    }

        // 打印歌词文件信息到控制台
    printf("\n----------歌词文件解析成功----------\n");
    printf("歌曲标题: %s\n", lyric_ctrl.current_lrc->title ? lyric_ctrl.current_lrc->title : "未知");
    printf("艺术家: %s\n", lyric_ctrl.current_lrc->artist ? lyric_ctrl.current_lrc->artist : "未知");
    printf("流派: %s\n", lyric_ctrl.current_lrc->genre ? lyric_ctrl.current_lrc->genre : "未知");
    printf("文件路径: %s\n", lrc_path);
     printf("运动标签: %s\n", lyric_ctrl.current_lrc->condition ? lyric_ctrl.current_lrc->condition : "未知");
    printf("歌词行数: %d\n", lyric_ctrl.current_lrc->line_count);

    // 打印所有歌词内容
    printf("歌词内容:\n");
    LyricLine *line = lyric_ctrl.current_lrc->lines;
    int line_count = 0;
    while (line) {
        printf("[%02d:%02d.%03d] %s\n",
               line->time.minute, line->time.second, line->time.millisecond,
               line->text);
        line = line->next;
        line_count++;
    }

    lyric_ctrl.has_lyric = true;
    lyric_update_display();
}

/**
 * @brief 清空歌词显示
 */
static void lyric_clear_display(void)
{
    for (int i = 0; i < LYRIC_VISIBLE_LINES; i++) {
        lv_label_set_text(lyric_ctrl.lines[i], "");
        lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_focus, 0);
        lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_normal, 0);
        lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_fade, 0);
    }

    // 显示无歌词提示
    lv_label_set_text(lyric_ctrl.lines[LYRIC_VISIBLE_LINES / 2], "暂无歌词");
    lv_obj_add_style(lyric_ctrl.lines[LYRIC_VISIBLE_LINES / 2], &lyric_ctrl.style_normal, 0);
}

/**
 * @brief 更新歌词显示内容
 */
static void lyric_update_display(void)
{
    if (!lyric_ctrl.has_lyric || !lyric_ctrl.current_lrc) {
        lyric_clear_display();
        return;
    }

    // 如果 focus_index 为 -1（歌曲已结束），清空显示
    if (lyric_ctrl.focus_index < 0) {
        lyric_clear_display();
        return;
    }

    LyricLine *current_line = lyric_ctrl.current_lrc->lines;
    int32_t line_count = lyric_ctrl.current_lrc->line_count;

    // 确保焦点索引在有效范围内
    if (lyric_ctrl.focus_index >= line_count) {
        // 如果焦点索引超出范围，显示最后一句歌词
        lyric_ctrl.focus_index = line_count - 1;
    }

    // 找到焦点行
    LyricLine *focus_line = current_line;
    for (int i = 0; i < lyric_ctrl.focus_index && focus_line; i++) {
        focus_line = focus_line->next;
    }

    if (!focus_line) {
        lyric_clear_display();
        return;
    }

    // 计算显示范围 - 确保不会超出歌词总数
    int32_t start_index = lyric_ctrl.focus_index - LYRIC_VISIBLE_LINES / 2;
    if (start_index < 0) start_index = 0;
    if (start_index + LYRIC_VISIBLE_LINES > line_count) {
        start_index = line_count - LYRIC_VISIBLE_LINES;
        if (start_index < 0) start_index = 0;
    }

    // 移动到起始行
    LyricLine *display_line = current_line;
    for (int i = 0; i < start_index && display_line; i++) {
        display_line = display_line->next;
    }

    // 更新每行显示
    for (int i = 0; i < LYRIC_VISIBLE_LINES; i++) {
        int32_t line_index = start_index + i;

        // 检查是否还有歌词行可显示
        if (display_line && line_index < line_count) {
            // 设置文本
            lv_label_set_text(lyric_ctrl.lines[i], display_line->text);

            // 清除所有样式
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_focus, 0);
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_normal, 0);
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_fade, 0);

            // 根据行位置设置样式
            if (line_index == lyric_ctrl.focus_index) {
                // 焦点行
                lv_obj_add_style(lyric_ctrl.lines[i], &lyric_ctrl.style_focus, 0);
            } else if (line_index < lyric_ctrl.focus_index) {
                // 已播放行（淡化）
                lv_obj_add_style(lyric_ctrl.lines[i], &lyric_ctrl.style_fade, 0);
            } else {
                // 未播放行（普通）
                lv_obj_add_style(lyric_ctrl.lines[i], &lyric_ctrl.style_normal, 0);
            }

            display_line = display_line->next;
        } else {
            // 没有更多歌词行，清空这一行
            lv_label_set_text(lyric_ctrl.lines[i], "");
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_focus, 0);
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_normal, 0);
            lv_obj_remove_style(lyric_ctrl.lines[i], &lyric_ctrl.style_fade, 0);
        }
    }
}
/**
 * @brief 滚动到焦点行
 */
static void lyric_scroll_to_focus(void)
{
    if (!lyric_ctrl.has_lyric) {
        return;
    }

    // 计算焦点行在容器中的位置
    int32_t focus_pos = lyric_ctrl.focus_index * LYRIC_LINE_HEIGHT;
    int32_t container_height = LYRIC_LINE_HEIGHT * LYRIC_VISIBLE_LINES;
    int32_t target_y = focus_pos - container_height / 2 + LYRIC_LINE_HEIGHT / 2;

    // 限制滚动范围
    int32_t max_scroll = lyric_ctrl.current_lrc->line_count * LYRIC_LINE_HEIGHT - container_height;
    if (target_y < 0) target_y = 0;
    if (target_y > max_scroll) target_y = max_scroll;

    // 执行滚动动画
    lv_obj_scroll_to_y(lyric_ctrl.cont, target_y, LV_ANIM_ON);
}

/**
 * @brief 根据当前时间查找歌词行索引
 * @param current_time 当前时间（毫秒）
 * @return 歌词行索引，-1表示未找到
 */
static int32_t lyric_find_current_index(long current_time)
{
    if (!lyric_ctrl.has_lyric || !lyric_ctrl.current_lrc) {
        return 0;
    }

    LyricLine *line = lyric_ctrl.current_lrc->lines;
    int32_t index = 0;
    int32_t best_index = 0;
    long best_time_diff = 0x7FFFFFFF;
    LyricLine *last_line = NULL;
    int32_t last_index = 0;

    // 查找最后一句歌词
    while (line) {
        last_line = line;
        last_index = index;
        line = line->next;
        index++;
    }

    // 如果当前时间超过最后一句歌词的时间，但仍然在歌曲时长内，显示最后一句歌词
    if (last_line && current_time >= last_line->time.timestamp) {
        // 获取歌曲总时长（秒转换为毫秒）
//        uint32_t track_length_ms = lrc->length * 1000;  // 使用length标签
        uint32_t track_length_ms = _lv_demo_music_get_track_length(lyric_ctrl.current_track_id) * 1000;

        // 如果当前时间还在歌曲时长内，显示最后一句歌词
        if (current_time <= track_length_ms) {
            return last_index;
        } else {
            // 歌曲已结束，不显示歌词
            return -1;
        }
    }

    // 正常查找最接近当前时间的歌词行
    line = lyric_ctrl.current_lrc->lines;
    index = 0;
    best_index = 0;
    best_time_diff = 0x7FFFFFFF;

    while (line) {
        long time_diff = current_time - line->time.timestamp;
        if (time_diff >= 0 && time_diff < best_time_diff) {
            best_time_diff = time_diff;
            best_index = index;
        }
        line = line->next;
        index++;
    }

    return best_index;
}

